package com.music.note_android.data.database

import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.room.TypeConverters
import android.content.Context
import com.music.note_android.data.model.Note
import com.music.note_android.data.model.Folder
import com.music.note_android.data.database.dao.NoteDao
import com.music.note_android.data.database.dao.FolderDao

/**
 * Room数据库配置
 * 管理笔记应用的本地数据库
 */
@Database(
    entities = [Note::class, Folder::class],
    version = 2,
    exportSchema = false
)
abstract class NoteDatabase : RoomDatabase() {
    
    /**
     * 获取笔记DAO
     */
    abstract fun noteDao(): NoteDao
    
    /**
     * 获取文件夹DAO
     */
    abstract fun folderDao(): FolderDao
    
    companion object {
        @Volatile
        private var INSTANCE: NoteDatabase? = null
        
        private const val DATABASE_NAME = "note_database"
        
        /**
         * 获取数据库实例（单例模式）
         */
        fun getDatabase(context: Context): NoteDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext,
                    NoteDatabase::class.java,
                    DATABASE_NAME
                )
                    .fallbackToDestructiveMigration() // 开发阶段允许破坏性迁移
                    .build()
                INSTANCE = instance
                instance
            }
        }
        
        /**
         * 清理数据库实例（主要用于测试）
         */
        fun clearInstance() {
            INSTANCE = null
        }
    }
}